/*现金收支页面*/
import React, {Component} from 'react';
import {StatusBar, FlatList, Text, View, TouchableOpacity, TouchableWithoutFeedback, Image, TextInput, Button, StyleSheet, PixelRatio, Dimensions, TouchableHighlight, ToastAndroid, DeviceEventEmitter} from 'react-native';
import Modal from 'react-native-modalbox';
import {RadioGroup, RadioButton} from 'react-native-flexi-radio-button'
import ModalDropdown from 'react-native-modal-dropdown';

import NavBar from '../../widget/navBar';
import CXIcon from '../../../style/icon/CXIcon';
import styles, {mainBackgroundColor, white} from "../../../style/global";
import {fen_to_yuan, is} from "../../../utils";
import Tips from "react-native-root-tips";
import {Actions} from "react-native-router-flux";
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import storeActions from "../../../store/actions/store";
import DateTimePicker from "react-native-modal-datetime-picker";


class ReadyCash extends Component{
    constructor(props){
        super(props);
        this.cashPage = 1;
        this.state = {
            outOptions:[
                {
                    name:'日常支出',
                    key:'daily_cost'
                },
                {
                    name:'退货支出',
                    key:'reject_cost'
                },
                {
                    name:'其他支出',
                    key:'other_cost'
                }
            ],
            incomeOptions:[
                {
                    name:'销售收入',
                    key:'order'
                },
                {
                    name:'调货收入',
                    key:'transfer'
                },
                {
                    name:'其他收入',
                    key:'other'
                }
            ],
            currentItem:'',
            activeType:'payOut',
            amount:'',//输入金额
            note:'',//备注
            isLoadMore:'',
            res_meta:{},
            isDateTimePickerVisible: false,
            currentDate: ''
        }
    }

    _changeShowModal(){
        this.refs.showModal.open()
    }
    _changeCloseModal(){
        this.refs.showModal.close()
    }
    handleDatePicked(e) {
        if (new Date(e).getTime() > new Date().getTime()) {
            Tips.showFail('请选择正确的日期');
            this.setState({
                isDateTimePickerVisible: false
            });
            return
        }

        let date = new Date(e);
        let year = date.getFullYear();
        let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
        let Str = year + '-' + month;
        console.log(Str);
        this.setState({
            isDateTimePickerVisible: false,
            currentDate: Str
        });

        let {storeAction} = this.props;
        storeAction.getCashList(1,Str,(res)=>{
            if(res && res.data){
                this.setState({
                    res_meta:res.meta
                })
            }
        });
    }
    hideDateTimePicker(e) {
        this.setState({
            isDateTimePickerVisible: false
        });
    }
    //收入下拉列表 row
    _renderIncome(option, index, isSelected){
        return (
            <Text style={style.modalSelectItem}>
                {option.name}
            </Text>
        );
    }
    componentDidMount(){
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
        let Str = year + '-' + month;
        this.setState({
            currentDate: Str
        });

        let {storeAction} = this.props;
        storeAction.getCashList(1,'',(res)=>{
            if(res && res.data){
                this.setState({
                    res_meta:res.meta
                })
            }
        });
        //监听事件
        this.listener = DeviceEventEmitter.addListener('cashHasMore',(isLoadMore) => {
            this.setState({
                isLoadMore:isLoadMore
            })
        })
    }
    componentWillUnmount() {
        this.listener.remove();
    }
    //创建空布局
    _createEmptyView(){
        return (
            <View style={{height:'100%', alignItems:'center', justifyContent:'center',paddingVertical: 20}}>
                <Text style={{fontSize:16}}>
                    暂无列表数据!!!
                </Text>
            </View>
        );
    }
    //加载更多
    _onLoadMore(){
        if(this.state.isLoadMore){
            this.cashPage = this.cashPage + 1;
            let {storeAction} = this.props;
            storeAction.getCashList(this.cashPage,'');
        }
    }
    //支出下拉列表
    _renderOut(option, index, isSelected){
        return (
            <Text style={style.modalSelectItem}>
                {option.name}
            </Text>
        );
    }
    //收入下拉选项显示文本
    _renderIncomeText(option){
        return option.name;
    }
    //支出下拉选项显示文本
    _renderOutText(option){
        return option.name;
    }
    //选中收入支出下拉事件
    _selectIncome(index,item){
        if(item){
            this.setState({
                currentItem: item
            })
        }
    }
    //选中支出下拉事件
    _selectOut(index,item){
        if(item){
            this.setState({
                currentItem: item
            })
        }
    }
    //切换支出，收入
    _changeTab(type){
        this.setState({
            activeType:type,
            currentItem:''
        })
    }
    //判断渲染下拉框
    _renderWhich(){
        if(this.state.activeType == 'income'){
            return(
                <ModalDropdown style={style.modalInput} textStyle={{color: '#4B8AF2', fontSize: 20}} defaultValue='请选择收支类型' options={this.state.incomeOptions} renderRow={(option, index, isSelected) => this._renderIncome(option, index, isSelected)} renderButtonText={(option) => this._renderIncomeText(option)} onSelect={(index, item) => this._selectIncome(index, item)}>

                </ModalDropdown>
            )
        } else {
            return(
                <ModalDropdown style={style.modalInput} textStyle={{color: '#4B8AF2', fontSize: 20}} defaultValue='请选择收支类型' options={this.state.outOptions} renderRow={(option, index, isSelected) => this._renderOut(option, index, isSelected)} renderButtonText={(option) => this._renderOutText(option)} onSelect={(index, item) => this._selectOut(index, item)}>

                </ModalDropdown>
            )
        }
    }
    //输入框处理金额
    _changeInput(amount){
       let values = amount;
        values = values.replace(/[^\d\.]|^\./g, '').replace(/\.{2}/g, '.').replace(/^([1-9]\d*|0)(\.\d{1,2})(\.|\d{1})?$/, '$1$2').replace(/^0\d{1}/g, '0');
        this.setState({
            amount:values
        })

    }
    //点击确定按钮
    _clickSureCash(){
        let message = '';
        let {storeAction} = this.props;
        let amount = this.state.amount;
        if(!is.has(this.state.amount)){
            message = '请输入收支金额'
        } else if(!is.has(this.state.currentItem)){
            message = '请选择收支类型'
        }
        if(message){
            ToastAndroid.showWithGravity(message, ToastAndroid.SHORT, ToastAndroid.CENTER)
        }
        if(this.state.activeType == 'income'){
            amount = amount
        } else if(this.state.activeType == 'payOut') {
            amount = -amount
        }
        let data = {
            amount:amount,
            category:this.state.currentItem.key,
            remark:this.state.note
        }
        storeAction.addCash(data,(res)=>{
            let {storeAction} = this.props;
            if(res && res.status){
                this._changeCloseModal();
                this.setState({
                    amount:''
                });
                storeAction.getCashList(1);
            }
        })
    }
    //渲染列表
    _renderCashList(rowDate,index){
        return(
            <View style={style.flatLi}>
                <Text style={style.item}>{is.time(rowDate.created_at)}</Text>
                <Text style={style.item}>{rowDate.cash_type}</Text>
                <Text style={style.item}>{rowDate.cash_category}</Text>
                <Text style={style.item}>{fen_to_yuan(rowDate.amount)}</Text>
                <Text style={style.lastItem} numberOfLines={1}>{rowDate.remark}</Text>
            </View>
        )
    }


    render() {
        let{storeState} = this.props;
        return (
           <View>
               <StatusBar hidden={true} />
               {/*表头*/}
               <View style={style.tabTitle}>
                   {/*选择时间按钮*/}
                   <TouchableWithoutFeedback onPress={() => this.setState({isDateTimePickerVisible: true})}>
                       <View style={style.tabItem}>
                           <View style={style.timeBtn}>
                               <Text style={style.timeTxt}>{this.state.currentDate}</Text>

                               <CXIcon name='xiala' color='#FFFFFF' size={10}>

                               </CXIcon>
                           </View>
                       </View>
                   </TouchableWithoutFeedback>
                   {/*选择时间*/}
                   <DateTimePicker
                       isVisible={this.state.isDateTimePickerVisible}
                       onConfirm={(e) => this.handleDatePicked(e)}
                       onCancel={(e) => this.hideDateTimePicker(e)}
                   >

                   </DateTimePicker>


                   {/*收入总金额*/}
                    <View style={style.tabItem}>
                        <Text style={style.tabInfo}>收入：</Text>
                        <Text style={style.tabInfo}>¥ {fen_to_yuan(this.state.res_meta.income)}</Text>
                    </View>
                   {/*总支出*/}
                   <View style={style.tabItem}>
                       <Text style={style.tabInfo}>支出：</Text>
                       <Text style={style.tabInfo}>¥ {fen_to_yuan(this.state.res_meta.outcome)}</Text>
                   </View>
                   {/*结余*/}
                   <View style={style.lastTabItem}>
                       <Text style={style.tabInfo}>结余：</Text>
                       <Text style={style.tabInfo}>¥ {fen_to_yuan(this.state.res_meta.diff)}</Text>
                   </View>

               </View>
               {/*表格*/}
               <View style={style.formList}>
                   <View style={style.formTitle}>
                       <Text style={style.itemFlex}>时间</Text>
                       <Text style={style.itemFlex}>类型</Text>
                       <Text style={style.itemFlex}>项目</Text>
                       <Text style={style.itemFlex}>金额</Text>
                       <Text style={style.lastItemFlex}>备注</Text>
                   </View>
                   {/*长列表*/}
                   <View>
                       <FlatList
                           style={{height:450}}
                           keyExtractor={(item, index) => index.toString()}
                           data={storeState.cashList}
                           renderItem={({item,index}) => this._renderCashList(item,index)}
                           onEndReached = {()=> this._onLoadMore()}
                           onEndReachedThreshold={0.1}
                           extraData={storeState.cashList}
                           ListEmptyComponent={this._createEmptyView}
                       >
                       </FlatList>

                   </View>
               </View>
               {/*新增按钮*/}
               <View style={style.btnBox}>
                   <TouchableOpacity onPress={()=>this._changeShowModal()}>
                       <View style={style.outBtn}>
                           <Text style={style.btnColor}>新增</Text>
                       </View>
                   </TouchableOpacity>
               </View>
               {/*点击新增按钮,弹出内容*/}
               <View>
                   <Modal ref="showModal"
                   position="center"
                   backdropColor='black'
                   style={{backgroundColor:'transparent', width:660,justifyContent:'center'}}
                   coverScreen={true}
                   backdropPressToClose={false}
                   swipeToClose={false}
                   backdropOpacity={0.6}
                   >
                       <View style={style.modalBox}>
                           <View style={style.modalTitle}>
                               <TouchableWithoutFeedback onPress={() => this._changeTab('payOut')}>
                                   <Text style={[style.modalTitleItemLeft,this.state.activeType == 'payOut' ? style.modalTitleItemActive : '']}>支出</Text>
                               </TouchableWithoutFeedback>
                               <TouchableWithoutFeedback onPress={() => this._changeTab('income')}>
                                   <Text style={[style.modalTitleItemRight,this.state.activeType == 'income' ? style.modalTitleItemActive : '']}>收入</Text>
                               </TouchableWithoutFeedback>
                           </View>
                           <View style={style.modalBody}>
                               <View style={style.modalBodyItem}>
                                   <Text style={style.modalTxt}>金额</Text>
                                   <TextInput
                                       style={style.modalInput}
                                       onChangeText={(amount) => this._changeInput(amount)}
                                       value={this.state.amount}
                                   />
                               </View>
                               <View style={style.modalBodyItem}>
                                   <Text style={style.modalTxt}>金额</Text>
                                   {this._renderWhich()}
                                   <CXIcon name='xuanze' color='#909090' size={20} style={style.modalIcon}>

                                   </CXIcon>
                               </View>
                               <View style={style.modalBodyLastItem}>
                                   <Text style={style.modalTxt}>备注</Text>
                                   <TextInput style={style.modalLastInput}
                                              multiline={true}
                                              textAlignVertical={'top'}
                                              onChangeText={(note) =>this.setState({note})}
                                   />
                               </View>

                           </View>
                           <View style={style.modalBtn}>
                               <TouchableOpacity onPress={() => this._changeCloseModal()}>
                                   <Text style={style.cancelBtn}>取消</Text>
                               </TouchableOpacity>
                               <TouchableOpacity onPress={() => this._clickSureCash()}>
                                   <Text style={style.sureBtn}>确认</Text>
                               </TouchableOpacity>

                           </View>

                       </View>
                   </Modal>
               </View>


           </View>
        );
    }
}
const style = StyleSheet.create({
    tabTitle: {
        flexDirection:'row',
        alignItems:'center',
        height:80,
        paddingHorizontal: 26
    },
    flatLi:{
        flexDirection:'row',
        alignItems:'center',
        height:60,
        borderBottomWidth:1,
        borderBottomColor:'#F0F0F5'
    },
    //表头时间按钮
    timeBtn:{
        flexDirection: 'row',
        alignItems:'center',
        justifyContent:'center',
        width:150,
        height:44,
        backgroundColor:mainBackgroundColor,
        borderRadius:4,
    },
    item: {
        flex: 1,
        fontSize:14,
        color:'#4A4A4A'
    },
    lastItem:{
        fontSize:14,
        flex: 2,
        color:'#4A4A4A'
    },
    timeTxt:{
        fontSize:14,
        color: '#ffffff',
        paddingRight:14
    },
    tabItem:{
        flex: 1,
        flexDirection:'row',
        alignItems:'center'
    },
    lastTabItem:{
        flex: 3,
        flexDirection:'row',
        alignItems:'center'
    },
    tabInfo:{
        fontSize: 14,
        color:'#5E5E5E'
    },
    formList:{
        height:514,
        backgroundColor:'#ffffff',
        paddingHorizontal: 26,
        borderBottomWidth:1,
        borderBottomColor:'#DBDBDB'

    },
    formTitle:{
        flexDirection:'row',
        alignItems:'center',
        height:60,
        borderBottomWidth:1,
        borderBottomColor:'#F0F0F5'
    },
    itemFlex:{
        flex:1,
        color:'#909090',
        fontSize:14
    },
    lastItemFlex:{
        flex:2,
        color:'#909090',
        fontSize:14
    },
    btnBox:{
        flexDirection:'row',
        height:70,
        alignItems:'center',
        justifyContent:'center',
        borderTopWidth:1,
        borderTopColor:'#DBDBDB',
        backgroundColor:'#fff'
    },
    outBtn:{
        paddingHorizontal:60,
        paddingVertical:8,
        backgroundColor: mainBackgroundColor,
        borderRadius:4
    },
    btnColor:{
        color:'#ffffff',
        fontSize:18
    },
    modalBox:{
        backgroundColor:'#fff',
        borderRadius:4
    },
    modalTitle:{
        flexDirection:'row',
        height:60,
        borderBottomWidth:1,
        borderBottomColor:'#D8D8D8'
    },
    modalTitleItemLeft:{
        textAlign:'center',
        flex:1,
        height:59,
        lineHeight:59,
        color:'#4A4A4A',
        fontSize:18,
        borderTopLeftRadius:4,

    },
    modalTitleItemActive:{
        backgroundColor:mainBackgroundColor,
        color:'#fff'
    },
    modalTitleItemRight:{
        flex:1,
        textAlign:'center',
        height:60,
        lineHeight:60,
        color:'#4A4A4A',
        fontSize:18,
        borderTopRightRadius:4
    },
    modalBody:{
        paddingLeft:30,
        paddingBottom:100,
        borderBottomWidth:1,
        borderBottomColor:'#DBDBDB'
    },
    modalBodyItem:{
        flexDirection:'row',
        alignItems:'center',
        height:90,
        borderBottomColor:'#D8D8D8',
        borderBottomWidth:1
    },
    modalBodyLastItem:{
        flexDirection:'row',
        paddingTop:28,
        paddingRight:60
    },
    modalTxt:{
        color:'#4A4A4A',
        fontSize:16,
        paddingRight: 56
    },
    modalInput:{
        flex:1,
        fontSize:18,
        color:'#4B8AF2'
    },
    modalSelectItem:{
        width:'100%',
        padding:10

    },
    modalIcon:{
        paddingRight:60
    },
    modalLastInput:{
        color:'#333333',
        fontSize:16,
        lineHeight:23,
        paddingHorizontal:30,
        paddingVertical: 16,
        borderWidth:1,
        borderColor:'#D7D7D7',
        backgroundColor:'#F3F3F3',
        borderRadius:4,
        height:90,
        flex:1
    },
    modalBtn:{
        height:90,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    },
    cancelBtn:{
        width:160,
        height:44,
        lineHeight:44,
        textAlign:'center',
        backgroundColor:'#909090',
        borderRadius:4,
        color:"#fff",
        fontSize:18,
        marginRight:84
    },
    sureBtn:{
        width:160,
        height:44,
        lineHeight:44,
        textAlign:'center',
        backgroundColor:mainBackgroundColor,
        borderRadius:4,
        color:"#fff",
        fontSize:18,
    }


})
export default connect(state =>({
    storeState: state.store
}),dispatch =>({
    storeAction: bindActionCreators(storeActions,dispatch)
}))(ReadyCash);
/*对Promiss的理解
* 名词解释：同步任务和异步任务
* 同步任务：只需要JS引擎自身就可以完成的任务
* 异步任务：JS引擎自身无法完成，需要外力协助的任务叫异步任务；还有一种
* 是由JS引擎能够独立完成，但是JS引擎把任务分成了两段，第二段当做回调，
* 也是异步任务*/